<?php


namespace app\xiangji\services;


use app\common\caches\UserCache;
use app\common\facades\auth\Auth;
use app\common\helpers\Response;
use app\common\models\User;
use app\common\models\UserLover;
use app\common\models\UserSignsRecord;
use app\xiangji\caches\ScoreRankCache;
use app\xiangji\exception\BadRequestException;
use app\xiangji\exception\ServiceUnavailableException;
use Ramsey\Uuid\Uuid;
use think\Exception;
use think\facade\Db;

class UserLoverService
{
    private $loveScoreLogService;

    public function __construct(LoveScoreLogService $loveScoreLogService)
    {
        $this->loveScoreLogService  = $loveScoreLogService;
    }

    /**
     * @todo 生成邀请token
     * @return array
     * @throws \GuzzleHttp\Exception\InvalidArgumentException
     * @throws \think\Exception
     */
    public function generateLoverBindToken()
    {
        $user = Auth::guard('api')->user();
        if ($user->lover->lover_id > 0){
            throw new BadRequestException('您已经绑定了您的TA', Response::HTTP_BAD_REQUEST);
        }
        $token = Uuid::uuid1();
        UserCache::setInviteLoverToken($token, $user);
        return ['token' => $token];
    }

    /**
     * @todo 通过token绑定恋人
     * @param $token    邀请token
     * @return bool
     * @throws \GuzzleHttp\Exception\InvalidArgumentException
     * @throws \think\Exception
     */
    public function bindLoverByToken($token)
    {
        $user = Auth::guard('api')->user();
        if ($user->lover->lover_id > 0){
            throw new BadRequestException('您已经绑定了您的TA', Response::HTTP_BAD_REQUEST);
        }
        $invite_user = UserCache::getInviteLoverToken($token);
        // 无缓存，直接失效
        if (!$invite_user){
            throw new BadRequestException('该邀请链接已失效', Response::HTTP_BAD_REQUEST);
        }
        // 自己不能绑定自己
        if ($invite_user->id == $user->id){
            throw new BadRequestException('自己不能绑定自己哟', Response::HTTP_BAD_REQUEST);
        }
        // 对方已绑定恋人
        if ($invite_user->lover->lover_id > 0){
            throw new BadRequestException('对方已经绑定了他的TA', Response::HTTP_BAD_REQUEST);
        }
        $this->bindLover($user, $invite_user);  // 绑定恋人关系
        // 清除token缓存
        UserCache::removeInviteLoverToken($token);
        return true;
    }

    // 绑定关系
    public function bindLover(User $user, User $lover)
    {
        $user->lover->lover_id = $lover->id;
        $lover->lover->lover_id = $user->id;
        $user->lover->bind_time = $lover->lover->bind_time = time();
        Db::startTrans();
        try {
            // 添加1314恋爱配对记录（按性别）*********************
            $userPair = new UserSignsRecord();
            //$male_id = $user->gender == 1 ? $user->id : $lover->id;
            if($user->gender == $lover->gender){
                return false;
            }
            if($user->gender == 1){
                $male_id = $user->id;
            }
            if($user->gender == 0){
                $female_id = $user->id;
            }
            if($lover->gender == 1){
                $male_id = $lover->id;
            }
            if($lover->gender == 0){
                $female_id = $lover->id;
            }
            $userPair::create([
                "male_id" =>$male_id,
                "female_id"=>$female_id,
                "bind_time"=>time()
            ]);
            //*******************************************
            $user->lover->save();
            $lover->lover->save();
            Db::commit();
            // 缓存绑定
            ScoreRankCache::loverBind($user->id, $lover->id);
            ScoreRankCache::loverBind($lover->id, $user->id);
            // 更新恩爱值排行
            ScoreRankCache::setScore(implodeUserId($user->id, $lover->id), intval(ScoreRankCache::getUserScore($user->id) + ScoreRankCache::getUserScore($lover->id)));
        } catch (\Exception $e){
            throw new ServiceUnavailableException('系统错误，请稍后再试', Response::HTTP_SERVICE_UNAVAILABLE);
            Db::rollback();
        }
        return true;
    }

    /**
     * @todo 解绑恋人
     * @return bool
     * @throws Exception
     */
    public function unbindLover()
    {
        $user = Auth::guard('api')->user();
        $lover = UserService::getUserLover($user);
        if (!$lover){
            throw new BadRequestException('未绑定恋人，不能解绑', Response::HTTP_FORBIDDEN);
        }
        Db::startTrans();
        try {
            // 更新恩爱值账户
            LoveScoreService::updateUserScore($user->loveScore, 0 - $user->loveScore->total_score, '解绑恋人，清空账户');
            // 添加恋人恩爱值账户变化记录
            LoveScoreService::updateUserScore($lover->loveScore, 0 - $lover->loveScore->total_score, '解绑恋人，清空账户');
            // 更新本人和恋人的关系中间库
            UserLover::whereIn('user_id', [$user->id, $lover->id])->save(['lover_id' => 0]);
            Db::commit();
            // 缓存绑定
            ScoreRankCache::loverBind($user->id, 0);
            ScoreRankCache::loverBind($lover->id, 0);
            // 清空恩爱值缓存
            ScoreRankCache::userScore($user->id, 0);
            ScoreRankCache::userScore($lover->id, 0);
            // 删除两人排行榜数据
            ScoreRankCache::removeScore(implodeUserId($user->id, $lover->id));
        } catch (Exception $exception){
            throw new ServiceUnavailableException('系统错误，请稍后再试', Response::HTTP_SERVICE_UNAVAILABLE);
            Db::rollback();
        }
        return true;
    }
}
